//
//  ZDOAuthViewController.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/10/28.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZDOAuthViewController: UIViewController {
    
    override func loadView() {
        
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "cancel")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Done, target: self, action: "autoFill")
        
        automaticallyAdjustsScrollViewInsets = false
        
        let url = ZDNetworkTool.sharedInstance.authURL()
        
        webView.loadRequest(NSURLRequest(URL: url))
    }

    /// 自动填充账号密码
    func autoFill() {
        let js = "document.getElementById('userId').value='925462931@qq.com';" + "document.getElementById('passwd').value='a910911804';"
        
        // webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    
    //MARK: - 取消 回调方法
    func cancel() {
    
        //移除提示框
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //MARK: - 懒加载
    lazy var webView: UIWebView = {
    
        let webView = UIWebView()
        
        webView.delegate = self
        
        return webView
    }()

}


//MARK: - 在当前类的延展中管理 UIWebViewDelegate 代理方法
extension ZDOAuthViewController: UIWebViewDelegate {

    //已经开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("正在拼命加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    //加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    
    /*
    
     点击取消 http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
     
     点击授权 http://www.baidu.com/?code=4236cab3a432023efe34aec1dc98ac53

    */
    
    
    //是否应该加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("request = \(request)")
        
        let prefix = ZDNetworkTool.sharedInstance.redirect_uri
        
        let urlString = request.URL?.absoluteString
        
        if !(urlString!.hasPrefix(prefix)) {
        
            return true
        }
        
        let query = request.URL?.query
        
        let codePrefix = "code="
        
        if query!.hasPrefix(codePrefix) {
        
            //点击了授权
            let code = (query! as NSString).substringFromIndex(codePrefix.characters.count)
            
            print("code = \(code)")   // code = 6385e68add1e0d8ea98c44c5e5ae657e
            
            //请求accessToken
            loadAccessToken(code)
            
        }
        else
        {
            //点击了取消
            self.loadFail("授权失败...")
        }
        
        print("query = \(query)")
        
        return false   //返回false 表示不打开回调url
    }
    
    //MARK: - 抽取 请求accessToken 方法
    private func loadAccessToken(code: String) {
    
        //请求accessToken
        ZDNetworkTool.sharedInstance.loadAccessToken(code, finished: { (result, error) -> Void in
            
            if error != nil || result == nil {
                
                //请求失败
                print("error = \(error)")
                
                self.loadFail("网络不给力...")
            }
            else {
                //请求成功
                print("result = \(result)")
                
                //移除提示框
                SVProgressHUD.dismiss()
                
                let account = ZDAccount(dict: result!)
                
                print(account)
                
                //保存用户数据
                account.saveAccountData()
                
                //加载用户信息
                account.loadUserInfo({ (error) -> Void in
                    
                    if (error != nil) {
                        
//                        print(error)
                        
                        self.loadFail("网络不给力...")
                    }
                    else {
                        
                        //加载用户信息成功 退出登录界面
                        self.cancel()
                        
                        print("account = \(account)")
                        
                        //跳转到欢迎控制器
                        (UIApplication.sharedApplication().delegate as! AppDelegate).switchController(ZDWelcomeViewController())
                    }
                })
            }
        })
    }
    
    //加载请求失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
//        print("加载失败error = \(error)")
        
//        SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
    }
    
    
    //MARK: - 加载失败调用
    private func loadFail(message: String) {
    
        SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)
        
        //延迟1秒后退出
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            
            //退出
            self.cancel()    //block里面需要写调用者
        })
    }
}

